<?php

namespace App\Services;

use App\Models\UserRoleUniqueId;

class UserRoleUniqueIdService extends ServiceBase
{
    public function getOne($user_id, $server_id, $role_id)
    {
        $item = UserRoleUniqueId::whereRaw("user_id={$user_id} AND role_id={$role_id} AND server_id={$server_id}")->first();
        return $item;
    }

    public function getOrCreateUniqueId($user_id, $server_id, $role_id)
    {
        $item = $this->getOne($user_id, $server_id, $role_id);
        if (!$item) {
            try {
                $item = new UserRoleUniqueId;
                $item->create_time = time();
                $item->user_id = $user_id;
                $item->server_id = $server_id;
                $item->role_id = $role_id;
                $item->save();
            } catch (\Throwable $th) {
                $item = $this->getOne($user_id, $server_id, $role_id);
            }
        }

        return $item->id;
    }
}
